from scripts.initdatabase import init_database

init_database()

import streamlit as st
from tools.verification import *
from tools.email_sender import EmailSender
from tools.DBUtil import DBUtil
from datetime import datetime
from time import sleep
from tools.SecureCookieManager import SecureCookieManager
from tools.encode_data import encrypt_password,decrypt_password

@st.dialog("登录")
def login():
    username = st.text_input("用户名")
    password = st.text_input("密码", type="password")
    if st.button("登录", key="login_button"):
        # 加密密码
        password = encrypt_password(password)
        if is_correct_username_password(username, password):
            st.success("登录成功")
            cookie_manager.create_signed_cookie("username", username)
            st.rerun()
        else:
            st.error("用户名或密码错误")

@st.dialog("注册")
def register():
    if "verifi_code" not in st.session_state:
        st.session_state.verifi_code = ""
    if "email" not in st.session_state:
        st.session_state.email = ""
    options = ["","厂站系统组", "主站系统组", "系统平台组", "系统应用组", "研发测试组", "测控技术组", "通讯技术组", "其它"]

    usergroup = st.selectbox("组别", options, index=0,key="usergroup") 
    username = st.text_input("用户名",placeholder="使用姓名中文")
    password = st.text_input("密码", type="password")
    email = st.text_input("邮箱",placeholder="使用公司OA邮箱,如xxx@cyg.com")

    col1, col2 = st.columns([7,3])
    verificationcode = col1.text_input("验证码")
    col2.markdown(f'<p style="margin-bottom: 28px;"></p>', unsafe_allow_html=True)
    getcodebutton = col2.button("获取验证码")
    registerbutton = st.button("注册",key="register_button")
    register_message = st.empty()

    if getcodebutton:
        # 邮箱验证
        if not is_valid_email(email):
            register_message.error("邮箱格式错误")
            return
        if is_valid_email_exist(email):
            register_message.error("邮箱已注册,请更换邮箱")
            return
        
        # 验证码生成
        verifi_code = generate_verification_code()
        st.session_state.verifi_code = verifi_code
        st.session_state.email = email

        # 发送验证码
        if EmailSender().send_email(email, "注册邮箱验证码", "您的验证码为: " + verifi_code):
            register_message.success("验证码已发送至邮箱")
        else:
            register_message.error("验证码发送失败，请检查邮箱是否正确")

    if registerbutton:
        if usergroup and username and password and email and verificationcode:
            print(f"提交的信息: ",usergroup, username, password, email, verificationcode)
            if is_valid_username_exist(username):
                register_message.error("用户名已经注册或不存在,请直接登录或联系管理员添加用户")
                return
            if st.session_state.verifi_code == "" or st.session_state.email == "":
                register_message.error("请先获取验证码")
                return
            if email == st.session_state.email and verificationcode == st.session_state.verifi_code:
                # 注册成功
                register_message.success("注册成功")
                # 加密密码
                password = encrypt_password(password)
                # 写入数据库
                DBUtil.uid_db("UPDATE user set passwd=%s,usergroup=%s,oamail=%s,registertime=%s WHERE username=%s",(password, usergroup, email, datetime.now(), username,))
                # 重置session
                st.session_state.verifi_code = ""
                st.session_state.email = ""
                sleep(2)
                st.rerun()
            else:
                register_message.error("邮箱或验证码非验证时信息，请重新绑定邮箱或获取验证码")
                return
        else:
            register_message.error("请填写完整信息")
            return

def normal_navigation():
    # 页面导航
    pages = {
        "个人中心": [
            st.Page("./templates/create_vmware.py", title="创建虚拟机"),
        ],
        "管理中心": [
            st.Page("./templates/manage_vmware.py", title="云虚拟机管理"),
        ],
    }

    pg1 = st.navigation(pages)
    pg1.run()

def leader_navigation():
    # 页面导航
    pages = {
        "个人中心": [
            st.Page("./templates/create_vmware.py", title="创建虚拟机"),
        ],
        "管理中心": [
            st.Page("./templates/manage_vmware.py", title="云虚拟机管理"),
            st.Page("./templates/manage_user.py", title="用户管理"),
        ],
    }

    pg2 = st.navigation(pages)
    pg2.run()


def admin_navigation():
    # 页面导航
    pages = {
        "个人中心": [
            st.Page("./templates/create_vmware.py", title="创建虚拟机"),
        ],
        "管理中心": [
            st.Page("./templates/system_config.py", title="系统配置"),
            st.Page("./templates/manage_vpShere.py", title="云虚拟机平台管理"),
            st.Page("./templates/manage_group.py", title="组别管理"),
            st.Page("./templates/manage_vmware.py", title="云虚拟机管理"),
            st.Page("./templates/manage_user.py", title="用户管理"),
            st.Page("./templates/manage_history.py", title="历史记录"),
        ],
    }

    pg3 = st.navigation(pages)
    pg3.run()

# ==================================================页面内容控制========================================================
st.set_page_config(page_title="虚拟主机自助申请系统", page_icon=":computer:",layout='wide')
cookie_manager = SecureCookieManager()
# 开启移除空元素的功能
st.markdown(
    f""" 
        <style>
            .element-container:has(iframe[height="0"]) {{ display: none; }}
        </style>
    """, unsafe_allow_html=True
)

# 添加自定义CSS来减少顶部间距
st.markdown(
    """
    <style>
    .block-container {
        padding-top: 1rem; /* 减少顶部间距 */
        padding-bottom: 0rem; /* 也可以减少底部间距 */
    }
    </style>
    """,
    unsafe_allow_html=True
)

username = cookie_manager.get_cookie("username")

if username:
    leader_list = DBUtil.select_all("select username from user,config_group where adminemail = oamail;")
    leader_list = [leader["username"] for leader in leader_list]
    print(leader_list)
    # 用户已登录，侧边栏内容
    if username == "admin":
        admin_navigation()  # 调用管理员页面导航
    elif username in leader_list:
        leader_navigation()  # 调用领导页面导航
    else:
        normal_navigation()  # 调用普通用户页面导航
    if st.sidebar.button("退出登录", key="logout"):
        cookie_manager.remove_cookie("username")
        st.rerun()
else:
    # 用户未登录，正文内容
    st.markdown(        # 解决退出登录后页面仍然显示侧边栏的bug
        """
        <style>
        [data-testid="stSidebarNav"] {display: none;}
        </style>
        """,
        unsafe_allow_html=True
    )
    col1, col2, col3, col4 = st.sidebar.columns([1, 5, 5, 1])
    if col2.button("登录", key="login"):
        login()  # 调用登录函数
    if col3.button("注册", key="register"):
        register()  # 调用注册函数

    st.html("<strong>说明文档</strong>: <a href='http://10.6.220.220:8090/pages/viewpage.action?pageId=40501389' target='_blank'>虚拟机自助申请系统使用说明</a>")
    st.html('''<strong>更新记录</strong>: <br/>
            2024/12/05 <br/>
            - 增加添加虚拟机权限功能<br/>
            - 优化查找虚拟机提示信息<br/>
    ''')